<script setup lang="ts">
import type {
  SysMenuQo,
  SysMenuTreeVo,
} from '#/system/menu'
import {
  createSysMenuApi,
  getSysMenuDetailsApi,
  getSysMenuTreeApi,
  updateSysMenuApi,
} from '@/api/system/menu'

interface OnCloseResolveType extends CloseResolveType {}
let onCloseResolve = function (_value: OnCloseResolveType) { }

const dialogRef = $ref<DialogInstance>()
const ruleFormRef = ref<FormInstance>()
let menuTree = $ref<SysMenuTreeVo[]>([])
let dialogModal = $ref<SysMenuQo>({})
let dialogAction = $ref<DialogAction>('add')
let confirmLoading = $ref(false)
let dialogLoading = $ref(false)
let pid = $ref<string>()

const rules = reactive<FormRules<SysMenuQo>>({
  title: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入组件名称', trigger: 'blur' },
  ],
  perms: [
    { required: true, message: '请输入权限标识符', trigger: 'blur' },
  ],
  path: [
    { required: true, message: '请输入组件地址', trigger: 'blur' },
  ],
  frameSrc: [
    { required: true, message: '请输入链接地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的链接地址', trigger: ['blur', 'change'] },
  ],
  menuRank: [
    { required: true, message: '请输入菜单排序', trigger: 'blur' },
  ],
})

async function getDefaultModel() {
  return {
    menuType: '1',
    menuRank: 1,
    showLink: 1,
    keepAlive: 1,
    showTag: 1,
  } as SysMenuQo
}
// 打开
async function showDialog(args: {
  title: string
  action?: DialogAction
  model: {
    id?: string
  }
}) {
  const dialogRes = dialogRef!.openDialog<OnCloseResolveType>({
    title: args.title,
  })

  ruleFormRef.value?.clearValidate()
  onCloseResolve = dialogRes.onCloseResolve

  dialogAction = args.action ?? 'add'

  if (args.model.id) {
    dialogModal.id = args.model.id
  }

  if (args.action === 'add') {
    const defaultModel = await getDefaultModel()
    dialogModal = {
      ...defaultModel,
      pid: args.model.id,
    }
    pid = args.model.id
  }
  else if (args.action === 'edit' || args.action === 'views') {
    await reflash()
  }
  await getSelectList()

  return await dialogRes.dialogPrm
}

async function reflash() {
  if (!dialogModal.id)
    return
  dialogLoading = true
  pid = ''
  const res = await getSysMenuDetailsApi(dialogModal.id)
  if (!res)
    return
  dialogLoading = false
  Object.assign(dialogModal, res.data)
  if (res.data.pid !== '0') {
    pid = res.data.pid
  }
}

async function getSelectList() {
  menuTree = (await getSysMenuTreeApi()).data
}

// 确认
async function confirm(formEl: FormInstance | undefined) {
  if (!formEl)
    return
  await formEl.validate(async (valid) => {
    if (!valid) {
      return
    }
    confirmLoading = true
    if (dialogAction === 'add') {
      await createSysMenuApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    else if (dialogAction === 'edit') {
      await updateSysMenuApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    confirmLoading = false
    Message({
      type: 'success',
      message: `${DialogActionMap[dialogAction as DialogAction]}成功`,
    })
    onCloseResolve({ type: true })
  })
}

// 取消
function cancel() {
  ruleFormRef.value?.clearValidate()
  onCloseResolve({ type: false })
}

defineExpose({ showDialog })
</script>

<template>
  <sy-dialog
    ref="dialogRef"
    :before-close="cancel"
    :hide-confirm="dialogAction === 'views'"
    :confirm-loading="confirmLoading"
    :disabled-confirm="dialogLoading"
    @confirm="confirm(ruleFormRef)"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="dialogLoading"
      :model="dialogModal"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item
        label="菜单类型"
        prop="menuType"
      >
        <sy-dict
          v-model="dialogModal.menuType"
          dict-type="menu_type"
          type="segmented"
        />
      </el-form-item>
      <el-form-item label="上级菜单" prop="pid">
        <el-tree-select
          v-model="pid"
          :data="menuTree"
          node-key="id"
          :render-after-expand="false"
          check-strictly
          clearable
          :props="{
            label: 'title',
          }"
          @change="() => {
            dialogModal.pid = pid
          }"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="title">
        <el-input
          v-model="dialogModal.title"
          placeholder="请输入菜单名称"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item
        v-if="dialogModal.menuType !== '3'"
        label="权限标识"
        prop="perms"
      >
        <el-input
          v-model="dialogModal.perms"
          placeholder="请输入权限标识"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <template v-if="dialogModal.menuType === '1'">
        <el-form-item label="组件名称" prop="name">
          <el-input
            v-model="dialogModal.name"
            placeholder="请输入组件名称"
            :disabled="dialogAction === 'views'"
          />
        </el-form-item>
        <el-form-item label="组件地址" prop="path">
          <el-input
            v-model="dialogModal.path"
            placeholder="请输入组件名称"
            :disabled="dialogAction === 'views'"
          />
        </el-form-item>
      </template>

      <template v-if="dialogModal.menuType === '3'">
        <el-form-item label="链接地址" prop="frameSrc">
          <el-input
            v-model="dialogModal.frameSrc"
            placeholder="请输入链接地址"
            :disabled="dialogAction === 'views'"
          />
        </el-form-item>
      </template>

      <template v-if="dialogModal.menuType === '1' || dialogModal.menuType === '3'">
        <el-form-item label="菜单图标" prop="icon">
          <sy-select-icon
            v-model="dialogModal.icon"
            placeholder="请选择菜单图标"
            :disabled="dialogAction === 'views'"
          />
        </el-form-item>
        <el-form-item label="菜单排序" prop="menuRank">
          <el-input
            v-model="dialogModal.menuRank"
            placeholder="请输入菜单排序"
            type="number"
            :min="0"
            :disabled="dialogAction === 'views'"
          />
        </el-form-item>
        <el-form-item label="标签栏" prop="showTag">
          <sy-dict
            v-model="dialogModal.showTag"
            dict-type="menu_show_tag"
            type="segmented"
          />
        </el-form-item>
        <el-form-item label="菜单显示" prop="menuRank">
          <sy-dict
            v-model="dialogModal.showLink"
            dict-type="menu_show_link"
            type="segmented"
          />
        </el-form-item>
        <el-form-item label="菜单缓存" prop="keepAlive">
          <sy-dict
            v-model="dialogModal.keepAlive"
            dict-type="menu_keep_alive"
            type="segmented"
          />
        </el-form-item>
      </template>
    </el-form>
  </sy-dialog>
</template>

<style scoped></style>
